package cn.o.app.util;

import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * 数字类，用于格式化double类型数字
 * 
 * @author shaka
 *
 */
public class ONumber {
	public static final String DECIMAL_POINT = ".";
	public static final String PATTERN_CURRENCY = "#.00";
	public static final String PATTERN_THOUSAND = "#,###.########";
	public static final String PATTERN_CURRENCY_THOUSAND = "#,###.00";

	protected double mNumber;
	protected String mPattern = "";
	protected String mInteger = "";// 整数部分
	protected String mDecimal = "";// 小数部分
	protected String mDecimalPart = "";// 小数点+小数部分

	public ONumber() {

	}

	public ONumber(Double number, String pattern) {
		mNumber = number;
		mPattern = pattern;
		doFormat();
	}

	public double getNumber() {
		return mNumber;
	}

	public void setNumber(double number) {
		mNumber = number;
		doFormat();
	}

	public String getPattern() {
		return mPattern;
	}

	public void setPattern(String pattern) {
		mPattern = pattern;
		doFormat();
	}

	public String getInteger() {
		return mInteger;
	}

	public String getDecimal() {
		return mDecimal;
	}

	public String getDecimalPart() {
		return mDecimalPart;
	}

	protected void doFormat() {
		if (mPattern == null) {
			return;
		}
		if (mPattern.isEmpty()) {
			return;
		}
		try {
			DecimalFormat decimalFormat = new DecimalFormat();
			decimalFormat.setRoundingMode(RoundingMode.FLOOR);
			mPattern = (mPattern == null ? "" : mPattern);
			decimalFormat.applyPattern(mPattern);

			String formattedNumber = decimalFormat.format(mNumber);
			int decimalPointIndex = formattedNumber.indexOf(DECIMAL_POINT);
			if (decimalPointIndex == -1) {
				mInteger = formattedNumber;
			} else {
				mInteger = formattedNumber.substring(0, decimalPointIndex);
				mDecimal = formattedNumber.substring(decimalPointIndex + 1);
				mDecimalPart = DECIMAL_POINT + mDecimal;
			}
		} catch (Exception e) {
			mInteger = "";
			mDecimal = "";
			mDecimalPart = "";
		}
	}

}
